package com.lzx.iteam;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.*;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.lzx.iteam.emotion.EmotionUtil;
import com.lzx.iteam.net.*;
import com.lzx.iteam.selectimage.Bimp;
import com.lzx.iteam.selectimage.Res;
import com.lzx.iteam.util.*;
import io.rong.imageloader.core.ImageLoader;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.lzx.iteam.widget.kpswitch.util.KPSwitchConflictUtil;
import com.lzx.iteam.widget.kpswitch.util.KeyboardUtil;
import com.lzx.iteam.widget.kpswitch.widget.KPSwitchPanelLinearLayout;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.*;

/**
 * 发表动态
 * Created by Megan on 15/10/12.
 */
public class SendTalkActivity extends Activity implements View.OnClickListener {


    private TextView mBack, mOk;
    private LinearLayout mEmotionLayout, mLlEmotionDots;
    private KPSwitchPanelLinearLayout mChatPanelRoot;
    private LinearLayout mLlImage;
    private ViewPager mVpEmotion;
    private ImageView mIvEmotion, mIvImage;
    private TextView mTvSendImage, mTvSendPhoto;
    private EditText mTalkContent;
    private HorizontalScrollView mImageHScrollView;
    private LinearLayout mImageHLinearLayout;
    private Bitmap mBitMap;
    private String mFilePath;
    private Dialog mWaitDialog;
    private int index = 0;
    private SendTalkActivity mActivity;

    private String mContentText;
    private JSONArray mContentImage;
    private List<Map<String, byte[]>> keyByte = new ArrayList<Map<String, byte[]>>();

    private final int SEND_TALK_MESSAGE = 1000;
    private final int GET_QN_TOKEN = 1001;
    private EmotionUtil mEmotionUtil;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SEND_TALK_MESSAGE:
                    httpReqDlgDismiss();
                    if (msg.arg1 == 0) {
                        ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(SendTalkActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                        if (Bimp.mPictureData.size() > 0){
                            Bimp.mPictureData.clear();
                        }
                        for(String data:Bimp.tempSelectBitmap){
                            Bimp.mPictureData.add(data);
                            Log.d("talk_list_send_da", data);
                        }
                        Bimp.tempSelectBitmap.clear();
                        Intent intent = new Intent(SendTalkActivity.this, TalkListActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        intent.setAction(TalkListActivity.CONTACTS_CIRCLE);
                        intent.putExtra("type", "score");
                        startActivity(intent);
                        finish();
                    }else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(SendTalkActivity.this, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(SendTalkActivity.this, (String) msg.obj,
                                    Toast.LENGTH_LONG).show();
                        }
                    }
                    break;

                case GET_QN_TOKEN:
                    if (msg.arg1 == 0) {
                        Map<String, Object> map = (HashMap<String, Object>) msg.obj;
                        for (int i = 0; i < keyByte.size(); i++) {
                            Map<String, byte[]> map1 = keyByte.get(i);
                            for (String key : map1.keySet()) {
                                setPhoto((String) map.get(key), map1.get(key), key);
                            }

                        }
                    }else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(SendTalkActivity.this, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(SendTalkActivity.this, (String) msg.obj,
                                    Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.send_talk_layout);
        mActivity = this;
        initView();
        Res.init(this);
        initEmotion();

        Log.d("InstanceState", "--onCreate   flag == "  + KPSwitchConflictUtil.mFlag);


        KeyboardUtil.attach(this, mChatPanelRoot,
                // Add keyboard showing state callback, do like this when you want to listen in the
                // keyboard's show/hide change.
                new KeyboardUtil.OnKeyboardShowingListener() {
                    @Override
                    public void onKeyboardShowing(boolean isShowing) {
                        Log.d("ChatActivity", String.format("Keyboard is %s", isShowing ? "showing" : "hiding"));
                    }
                });

        KPSwitchConflictUtil.attach(mChatPanelRoot, mIvEmotion, mIvImage, null, mTalkContent,
                new KPSwitchConflictUtil.SwitchClickListener() {
                    @Override
                    public void onClickSwitch(boolean switchToPanel, int flag) {

                        if (switchToPanel) {
                            mTalkContent.clearFocus();
                            Log.d("switchToPanel", " true ==  " + flag);
                            if (flag == 1) {
                                mIvEmotion.setImageDrawable(getResources().getDrawable(R.drawable.selector_keyboard_btn));
                                mIvImage.setImageDrawable(getResources().getDrawable(R.drawable.selector_send_image));
                                mEmotionLayout.setVisibility(View.VISIBLE);
                                mLlImage.setVisibility(View.GONE);
                            } else {
                                mIvEmotion.setImageDrawable(getResources().getDrawable(R.drawable.selector_emotion_icon));
                                mIvImage.setImageDrawable(getResources().getDrawable(R.drawable.selector_keyboard_btn));
                                mEmotionLayout.setVisibility(View.GONE);
                                mLlImage.setVisibility(View.VISIBLE);
                            }
                        } else {
                            mTalkContent.requestFocus();
                            mIvEmotion.setImageDrawable(getResources().getDrawable(R.drawable.selector_emotion_icon));
                            mIvImage.setImageDrawable(getResources().getDrawable(R.drawable.selector_send_image));
                            Log.d("switchToPanel", " false ==  " + flag);
                        }
                    }
                });

    }


    @Override
    protected void onResume() {
        super.onResume();
        setImageMsg();
        if (KPSwitchConflictUtil.mFlag == 2){
            Log.d("InstanceState", "--onResume  ==  showPanel " );
            KPSwitchConflictUtil.showPanel(mChatPanelRoot);
        }
    }

    private void initView() {
        mBack = (TextView) this.findViewById(R.id.tv_send_talk_cancle);
        mOk = (TextView) this.findViewById(R.id.tv_send_talk_ok);
        mTalkContent = (EditText) this.findViewById(R.id.et_send_talk_content);
        mChatPanelRoot = (KPSwitchPanelLinearLayout) findViewById(R.id.chat_panel_root);
        mImageHScrollView = (HorizontalScrollView) this.findViewById(R.id.create_talk_h_scrollview);
        mImageHLinearLayout = (LinearLayout) this.findViewById(R.id.create_talk_h_gallery);
        mIvEmotion = (ImageView) this.findViewById(R.id.create_talk_emotion_select);
        mIvImage = (ImageView) this.findViewById(R.id.create_talk_image_select);
        mEmotionLayout = (LinearLayout) findViewById(R.id.ll_emotion_layout);
        mVpEmotion = (ViewPager) findViewById(R.id.emotion_viewpager);
        mLlEmotionDots = (LinearLayout) findViewById(R.id.emotion_dots_container);
        mLlImage = (LinearLayout) findViewById(R.id.rl_chat_more);
        mTvSendImage = (TextView) findViewById(R.id.tv_chat_image);
        mTvSendPhoto = (TextView) findViewById(R.id.tv_chat_camera);
        mBack.setOnClickListener(this);
        mOk.setOnClickListener(this);
        mTalkContent.setOnClickListener(this);
        mTvSendImage.setOnClickListener(this);
        mTvSendPhoto.setOnClickListener(this);
    }



    private void initEmotion() {
        mEmotionUtil = new EmotionUtil(this, mTalkContent, mLlEmotionDots, mVpEmotion);
        mEmotionUtil.initStaticFaces();
        mEmotionUtil.initViewPager();
        mVpEmotion.setOnPageChangeListener(mEmotionUtil.new PageChange());
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_send_talk_cancle:
                ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(SendTalkActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                Bimp.deleteAllPhoto();
                mEmotionLayout.setVisibility(View.GONE);
                mLlImage.setVisibility(View.GONE);

                finish();
                break;
            case R.id.tv_send_talk_ok:
                httpReqDlgShow();
                mContentText = mTalkContent.getText().toString().trim();
                if (StringUtil.isEmpty(mContentText) && Bimp.tempSelectBitmap.size() == 0) {
                    Toast.makeText(this, "对不起，您没有填写内容", Toast.LENGTH_LONG).show();
                    httpReqDlgDismiss();
                    return;
                }
                if (Bimp.tempSelectBitmap.size() > 0) {
                    mContentImage = new JSONArray();
                    StringBuilder stringBuilder = new StringBuilder();
                    for (String image : Bimp.tempSelectBitmap) {
                        Map<String, byte[]> token = new HashMap<String, byte[]>();
                        String key = UUID.randomUUID().toString() + System.currentTimeMillis();
                        if (mBitMap != null) {
                            if (!mBitMap.isRecycled()) {
                                mBitMap.recycle();
                            }
                            mBitMap = null;
                        }
                        mBitMap = PhotoUtil.readBitmapFromPath(SendTalkActivity.this, image,true);
                        if (mBitMap != null && !mBitMap.isRecycled()) {
                            byte[] bytes = PhotoUtil.compressImage(mBitMap);
                            token.put(key, bytes);
                        }
                        stringBuilder.append(key + ",");
                        try {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("type", "1");
                            jsonObject.put("data", key);
                            mContentImage.put(jsonObject);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        keyByte.add(token);
                    }
                    getQnToken(stringBuilder.substring(0, stringBuilder.length() - 1));

                }
                sendTalkMsg();

                break;

            case R.id.tv_chat_image:
                Intent intent2 = new Intent(this, ImageFileActivity.class);
                startActivity(intent2);
                break;
            case R.id.tv_chat_camera:
                mFilePath = PhotoUtil.doTakePhotoEvent(this);
                break;
            case R.id.et_send_talk_content:
                KPSwitchConflictUtil.mFlag = 0;
                mIvEmotion.setImageDrawable(getResources().getDrawable(R.drawable.selector_emotion_icon));
                mIvImage.setImageDrawable(getResources().getDrawable(R.drawable.selector_send_image));
                break;
        }
    }

    /**
     * 发表动态
     */
    private void sendTalkMsg() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        if (!StringUtil.isEmpty(mContentText)) {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_TEXT, mContentText));
        }
        if (mContentImage != null && mContentImage.length() > 0) {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CONTENT, mContentImage.toString()));
        }
        SendTalkMsg message = new SendTalkMsg(mHandler.obtainMessage(SEND_TALK_MESSAGE), SendTalkActivity.this);
        message.mApi = AsynHttpClient.API_TALK_ADD;
        message.mParams = nvps;
        AsynHttpClient.getInstance(this).execTalkHttp(message);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case Constants.SELECT_IMG_BACK:
                if (resultCode == RESULT_OK) {
                    setImageMsg();
                } else if (resultCode == 100) {
                    String imgPath = data.getStringExtra(Constants.IMAGE_PATH);
                    Bimp.tempSelectBitmap.add(imgPath);
                    setImageMsg();
                }
                break;
            case PhotoUtil.CAMERA_WITH_DATAA:
                if (Bimp.tempSelectBitmap.size() < 9 && resultCode == RESULT_OK) {
                    Bitmap bitmap = PhotoUtil.readBitmapFromPath(this, mFilePath,false);
                    int degree = PhotoUtil.getExifOrientation(mFilePath);
                    if (degree != 0) {
                        bitmap = PhotoUtil.rotaingImageView(bitmap, degree);
                        FileUtils.deleteFolderFile(mFilePath, true);
                        mFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Yun/Images/" + PhotoUtil.saveBitmaptoSdCard(bitmap, "/Yun/Images");
                    }
                    Bimp.tempSelectBitmap.add(mFilePath);
                    setImageMsg();
                }
                break;
        }
    }


    private void setImageMsg() {
        int imgSize = 0;
        if (Bimp.tempSelectBitmap != null) {
            imgSize = Bimp.tempSelectBitmap.size();
            if (imgSize > 0) {
                mImageHScrollView.setVisibility(View.VISIBLE);
                mImageHLinearLayout.removeAllViews();
                for (int i = 0; i < Bimp.tempSelectBitmap.size(); i++) {
                    final String image = Bimp.tempSelectBitmap.get(i);
                    final int position = i;
                    final View view = LayoutInflater.from(SendTalkActivity.this).inflate(R.layout.ho_list_item, mImageHLinearLayout, false);
                    ImageView mIvDelete = (ImageView) view.findViewById(R.id.event_iv_item_delete);
                    ImageView mIvImage = (ImageView) view.findViewById(R.id.event_iv_item_image);
                    ImageLoader.getInstance().displayImage("file://" + image, mIvImage, ImageLoaderInterface.optionEventImage);

                    mIvDelete.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
//                            Bimp.tempSelectBitmap.remove(position);
                            Bimp.deletePhoto(image);
                            Bimp.tempSelectBitmap.remove(image);
                            mImageHLinearLayout.removeView(view);
//                            mImageHLinearLayout.removeViewAt(position);
                            if (Bimp.tempSelectBitmap.size() <= 0) {
                                showImageLayout(false);
                            } else {
                                showImageLayout(true);
                            }
                        }
                    });
                    mIvImage.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent = new Intent(SendTalkActivity.this, ImagePagerActivity.class);
                            intent.putExtra(Constants.IMAGE_ORIGIN, Constants.IMAGE_ORIGIN_LOCAL_ARRAY);
                            intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, Bimp.tempSelectBitmap);
                            intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, position);
                            startActivity(intent);
                        }
                    });
                    mImageHLinearLayout.addView(view);
                }


            } else {
                // mImageHListView.setVisibility(View.GONE);
                mImageHScrollView.setVisibility(View.GONE);
            }

        }

    }

    public void showImageLayout(boolean flag) {
        if (flag) {
            mImageHScrollView.setVisibility(View.VISIBLE);
        } else {
            mImageHScrollView.setVisibility(View.GONE);
        }
    }


    //设置图片
    public void setPhoto(String token, byte[] file, String fileName) {
        Log.d("七牛--token", token);
        Log.d("七牛--fileName", fileName);
        DialerApp.getUploadManager(this).put(file, fileName, token,
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject response) {
                        Log.d("七牛--info.isOk()", info.isOK() + "--response" + response);
                        ++index;
                        if (mContentImage.length() == index) {
                            mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    Bimp.deleteAllPhotoAfterSend();
                                    Constants.NEW_TALK_ID = "";
                                }
                            },3000);
                            Log.d("talk_list_send_da", " 发送完成 ");
                        }else{
                            Log.d("talk_list_send_da", " 发送还没有完成 ===== ");
                        }
                    }
                }, null);
    }


    public void getQnToken(String keys) {
        List<NameValuePair> mList = new ArrayList<NameValuePair>();
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_KEYS, keys));
        GetQnTokenMsg getQnTokenMsg = new GetQnTokenMsg(mHandler.obtainMessage(GET_QN_TOKEN));
        getQnTokenMsg.mApi = AsynHttpClient.API_TALK_GET_TALK_TOKEN;
        getQnTokenMsg.mParams = mList;
        AsynHttpClient.getInstance(this).execTalkHttp(getQnTokenMsg);
    }

    /**
     * 显示等待的dialog
     */
    private void httpReqDlgShow() {
        if (mWaitDialog == null) {
            mWaitDialog = AllDialogUtil.getInstance(mActivity).waitDialog();
//            mProgressDialog.setCancelable(false);
            mWaitDialog.show();
        }

    }

    /**
     * 取消等待的dialog
     */
    private void httpReqDlgDismiss() {
        if (mWaitDialog != null && mWaitDialog.isShowing()) {
            mWaitDialog.dismiss();
            mWaitDialog = null;
        }
    }

    /**
     * @param newConfig 处理横竖屏切换，activity 被杀死，网页音频重新播放的问题
     */
    @Override
    public void onConfigurationChanged(android.content.res.Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // 检测屏幕的方向：纵向或横向
        if (this.getResources().getConfiguration().orientation
              == android.content.res.Configuration.ORIENTATION_LANDSCAPE) {
            //当前为横屏， 在此处添加额外的处理代码
            Log.d("InstanceState", "--InstanceState  ==  横屏 " );

        } else if (this.getResources().getConfiguration().orientation
              == android.content.res.Configuration.ORIENTATION_PORTRAIT) {
            //当前为竖屏， 在此处添加额外的处理代码

            Log.d("InstanceState", " 竖屏  , flag == " + KPSwitchConflictUtil.mFlag + " size == " + Bimp.tempSelectBitmap.size());

            if (Bimp.tempSelectBitmap.size() > 0){
                KPSwitchConflictUtil.showPanel(mChatPanelRoot);
                mIvImage.setImageDrawable(getResources().getDrawable(R.drawable.selector_keyboard_btn));

            }

        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        // TODO 红米手机拍照 有时页面会被销毁 此时需要保存拍照地址
        outState.putString("pic_path", mFilePath);
        if (Bimp.tempSelectBitmap.size() > 0){
            outState.putStringArrayList("images",Bimp.tempSelectBitmap);
        }
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        // TODO 取出保存的拍照地址
        mFilePath = savedInstanceState.getString("pic_path");
        ArrayList<String> images = savedInstanceState.getStringArrayList("images");
        if (images != null && images.size() > 0){
            Bimp.tempSelectBitmap.clear();
            Bimp.tempSelectBitmap.addAll(savedInstanceState.getStringArrayList("images"));
        }
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:

                if (mChatPanelRoot.getVisibility() == View.VISIBLE) {
                    KPSwitchConflictUtil.hidePanelAndKeyboard(mChatPanelRoot);
                    mIvEmotion.setImageDrawable(getResources().getDrawable(R.drawable.selector_emotion_icon));
                    mIvImage.setImageDrawable(getResources().getDrawable(R.drawable.selector_send_image));
                    return true;
                }
                Bimp.deleteAllPhoto();
                break;
        }

        return super.onKeyDown(keyCode, event);
    }

}
